package simpledb;

import java.util.*;

/**
 * The Join operator implements the relational join operation.
 */
public class Join extends Operator {

    private static final long serialVersionUID = 1L;
    private final JoinPredicate predicate;
    private OpIterator child1;
    private OpIterator child2;
    private Tuple tempT1;

    /**
     * Constructor. Accepts two children to join and the predicate to join them
     * on
     * 
     * @param p
     *            The predicate to use to join the children
     * @param child1
     *            Iterator for the left(outer) relation to join
     * @param child2
     *            Iterator for the right(inner) relation to join
     */
    public Join(JoinPredicate p, OpIterator child1, OpIterator child2) {
        this.predicate = p;
        this.child1 = child1;
        this.child2 = child2;
    }

    public JoinPredicate getJoinPredicate() {
        return predicate;
    }

    /**
     * @return
     *       the field name of join field1. Should be quantified by
     *       alias or table name.
     * */
    public String getJoinField1Name() {
        int field = predicate.getField1();
        TupleDesc t = child1.getTupleDesc();
        return t.getFieldName(field);
    }

    /**
     * @return
     *       the field name of join field2. Should be quantified by
     *       alias or table name.
     * */
    public String getJoinField2Name() {
        int field = predicate.getField2();
        TupleDesc t = child2.getTupleDesc();
        return t.getFieldName(field);
    }

    /**
     * @see simpledb.TupleDesc#merge(TupleDesc, TupleDesc) for possible
     *      implementation logic.
     */
    public TupleDesc getTupleDesc() {
        ArrayList<Type> types = new ArrayList<>();
        ArrayList<String> names = new ArrayList<>();

        TupleDesc td1 = child1.getTupleDesc();
        TupleDesc td2 = child2.getTupleDesc();

        for (int i = 0; i < td1.numFields(); i++) {
            types.add(td1.getFieldType(i));
            names.add(td1.getFieldName(i));
        }

        for (int i = 0; i < td2.numFields(); i++) {
            types.add(td2.getFieldType(i));
            names.add(td2.getFieldName(i));
        }

        return new TupleDesc(types.toArray(new Type[0]), names.toArray(new String[0]));
    }

    public void open() throws DbException, NoSuchElementException,
            TransactionAbortedException {
        child1.open();
        child2.open();
        super.open();
    }

    public void close() {
        super.close();
        child2.close();
        child1.close();
    }

    public void rewind() throws DbException, TransactionAbortedException {
        child1.rewind();
        child2.rewind();
    }

    /**
     * Returns the next tuple generated by the join, or null if there are no
     * more tuples. Logically, this is the next tuple in r1 cross r2 that
     * satisfies the join predicate. There are many possible implementations;
     * the simplest is a nested loops join.
     * <p>
     * Note that the tuples returned from this particular implementation of Join
     * are simply the concatenation of joining tuples from the left and right
     * relation. Therefore, if an equality predicate is used there will be two
     * copies of the join attribute in the results. (Removing such duplicate
     * columns can be done with an additional projection operator if needed.)
     * <p>
     * For example, if one tuple is {1,2,3} and the other tuple is {1,5,6},
     * joined on equality of the first column, then this returns {1,2,3,1,5,6}.
     * 
     * @return The next matching tuple.
     * @see JoinPredicate#filter
     */
    protected Tuple fetchNext() throws TransactionAbortedException, DbException {
        if (tempT1 != null) {
            while (child2.hasNext()) {
                Tuple t = child2.next();

                if (!predicate.filter(tempT1, t)) {
                    continue;
                }

                Tuple newTuple = new Tuple(getTupleDesc());
                newTuple.setRecordId(tempT1.getRecordId());
                int numField1 = child1.getTupleDesc().numFields();
                for (int i = 0; i < numField1; i++) {
                    newTuple.setField(i, tempT1.getField(i));
                }
                for (int i = 0; i < child2.getTupleDesc().numFields(); i++) {
                    newTuple.setField(i + numField1, t.getField(i));
                }
                return newTuple;
            }
        }

        while (child1.hasNext()) {
            child2.rewind();
            tempT1 = child1.next();
            return fetchNext();
        }
        return null;
    }

    @Override
    public OpIterator[] getChildren() {
        return new OpIterator[] { child1, child2 };
    }

    @Override
    public void setChildren(OpIterator[] children) {
        child1 = children[0];
        child2 = children[1];
    }

}
